package com.hson.demo.base.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class WechatXmlUtil {

	private WechatXmlUtil() {}
	
	@SuppressWarnings("unchecked")
	public static Map<String, String> parsePostMap(String xmlData) throws DocumentException {
		// 将解析结果存储在HashMap中
		Map<String, String> map = new HashMap<String, String>();
		
		InputStream inputStream = new ByteArrayInputStream(xmlData.getBytes());
		// 读取字节流
		SAXReader reader = new SAXReader();
		Document document;
		try {
			document = reader.read(inputStream);
		} catch (DocumentException e) {
			throw e;
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		// 得到xml根元素
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<Element> elementList = root.elements();
		// 遍历所有子节点
		for (Element e : elementList) {
			map.put(e.getName(), e.getText());
		}
		map.put("xml", document.asXML());
		return map;
	}
	
	@SuppressWarnings("unchecked")
	public static Map<String, Object> parseXml2Map(String xmlData) throws DocumentException {
		// 将解析结果存储在HashMap中
		Map<String, Object> map = new HashMap<String, Object>();
		
		//InputStream inputStream = new ByteArrayInputStream(xmlData.getBytes());
		StringReader sr = new StringReader(xmlData);
		// 读取字节流
		SAXReader reader = new SAXReader();
		reader.setEncoding("UTF-8");
		Document document;
		try {
			document = reader.read(sr);
		} catch (DocumentException e) {
			throw e;
		} finally {
			if (sr != null) {
				sr.close();
			}
		}
		// 得到xml根元素
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<Element> elementList = root.elements();
		// 遍历所有子节点
		for (Element e : elementList) {
			map.put(e.getName(),e);
		}
		map.put("xml", document.asXML());
		return map;
	}
}
